<template>
  <div class="verification-code-input">
    <div class="code-inputs">
      <input
        v-for="(digit, index) in digits"
        :key="index"
        :ref="(el) => { if (el) inputRefs[index] = el as HTMLInputElement }"
        v-model="digits[index]"
        type="text"
        inputmode="text"
        maxlength="1"
        class="code-digit"
        :class="{ 'has-value': digits[index] }"
        @input="handleInput(index, $event)"
        @keydown="handleKeydown(index, $event)"
        @paste="handlePaste"
        @focus="handleFocus(index)"
        @beforeinput="handleBeforeInput(index, $event)" />
    </div>
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, nextTick } from 'vue';

  interface Props {
    modelValue?: string;
    error?: string;
    disabled?: boolean;
  }

  interface Emits {
    (e: 'update:modelValue', value: string): void;
    (e: 'complete', value: string): void;
    (e: 'change', value: string): void;
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    error: '',
    disabled: false,
  });

  const emit = defineEmits<Emits>();

  // 响应式数据
  const digits = ref(['', '', '', '', '', '']);
  const inputRefs = ref<(HTMLInputElement | null)[]>([]);

  // 监听外部值变化
  watch(
    () => props.modelValue,
    (newValue) => {
      if (newValue !== digits.value.join('')) {
        const newDigits = newValue.split('').slice(0, 6);
        digits.value = [...newDigits, ...Array(6 - newDigits.length).fill('')];
      }
    },
    { immediate: true }
  );

  // 监听内部值变化
  watch(
    digits,
    (newDigits) => {
      const value = newDigits.join('');
      emit('update:modelValue', value);
      emit('change', value);

      if (value.length === 6) {
        emit('complete', value);
      }
    },
    { deep: true }
  );

  // 处理输入前事件（用于安卓设备）
  const handleBeforeInput = (index: number, event: InputEvent) => {
    // 如果是插入文本操作，检查输入内容
    if (event.inputType === 'insertText' || event.inputType === 'insertCompositionText') {
      const inputData = event.data || '';
      
      // 如果输入多个字符，只取第一个有效字符
      if (inputData.length > 1) {
        event.preventDefault();
        const firstChar = inputData.charAt(0);
        if (/^[a-zA-Z0-9]$/.test(firstChar)) {
          digits.value[index] = firstChar;
          // 自动跳转到下一个输入框
          if (index < 5) {
            nextTick(() => {
              inputRefs.value[index + 1]?.focus();
            });
          }
        }
        return;
      }
      
      // 单个字符验证
      if (inputData && !/^[a-zA-Z0-9]$/.test(inputData)) {
        event.preventDefault();
        return;
      }
    }
  };

  // 方法
  const handleInput = (index: number, event: Event) => {
    const target = event.target as HTMLInputElement;
    let value = target.value;

    // 安卓设备可能绕过 maxlength，强制截断为单个字符
    if (value.length > 1) {
      value = value.charAt(0);
      target.value = value;
    }

    // 只允许数字和字母
    if (value && !/^[a-zA-Z0-9]$/.test(value)) {
      target.value = digits.value[index] || '';
      return;
    }

    // 确保只取第一个字符（防止安卓设备输入多个字符）
    const char = value.charAt(0) || '';
    digits.value[index] = char;
    
    // 如果输入了有效字符且不是最后一个输入框，自动跳转
    if (char && index < 5) {
      nextTick(() => {
        inputRefs.value[index + 1]?.focus();
      });
    }
  };

  const handleKeydown = (index: number, event: KeyboardEvent) => {
    const { key } = event;

    // 处理退格键
    if (key === 'Backspace') {
      if (!digits.value[index] && index > 0) {
        // 如果当前框为空，跳转到上一个框
        nextTick(() => {
          inputRefs.value[index - 1]?.focus();
        });
      } else {
        // 清空当前框
        digits.value[index] = '';
      }
    }

    // 处理方向键
    if (key === 'ArrowLeft' && index > 0) {
      const timer = setTimeout(() => {
        inputRefs.value[index - 1]?.focus();
        clearTimeout(timer);
      }, 100);
    }

    if (key === 'ArrowRight' && index < 5) {
      const timer = setTimeout(() => {
        inputRefs.value[index + 1]?.focus();
        clearTimeout(timer);
      }, 100);
    }

    // 处理数字和字母键（但不在这里设置值，让handleInput处理）
    if (/^[a-zA-Z0-9]$/.test(key)) {
      // 阻止默认行为，让handleInput处理
      // event.preventDefault();
      const target = event.target as HTMLInputElement;
      target.value = key;
      digits.value[index] = key;

      if (index < 5) {
        const timer = setTimeout(() => {
          inputRefs.value[index + 1]?.focus();
          clearTimeout(timer);
        }, 100);
      }
    }
  };

  const handlePaste = (event: ClipboardEvent) => {
    event.preventDefault();
    const pastedData = event.clipboardData?.getData('text') || '';
    const validChars = pastedData.replace(/[^a-zA-Z0-9]/g, '').slice(0, 6);
    if (validChars.length > 0) {
      const newDigits = [...validChars.split(''), ...Array(6 - validChars.length).fill('')];
      digits.value = newDigits;
      digits.value.forEach((item: any, index) => {
        item = newDigits[index] || '';
      });
      const findIndex = digits.value.findIndex((item: any) => !item) || 5;
      const time = setTimeout(() => {
        inputRefs.value[findIndex]?.focus();
        clearTimeout(time);
      }, 100);
    }
  };

  const handleFocus = (index: number) => {
    // 选中当前输入框的内容
    // nextTick(() => {
    //   const input = inputRefs.value[index];
    //   if (input) {
    //     input.select();
    //   }
    // });
  };

  // 清空所有输入
  const clear = () => {
    digits.value = ['', '', '', '', '', ''];
    nextTick(() => {
      inputRefs.value[0]?.focus();
    });
  };

  // 聚焦到第一个输入框
  const focus = () => {
    nextTick(() => {
      inputRefs.value[0]?.focus();
    });
  };

  // 暴露方法给父组件
  defineExpose({
    clear,
    focus,
  });
</script>

<style lang="scss" scoped>
  .verification-code-input {
    .code-inputs {
      display: flex;
      gap: 12px;
      justify-content: center;
      margin-bottom: 8px;
    }

    .code-digit {
      width: 48px;
      height: 48px;
      border: 2px solid #e0e0e0;
      border-radius: 8px;
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      color: #0a0a0a;
      background: #f4f5f7;
      transition: all 0.3s ease;
      outline: none;

      &:hover {
        border-color: #f76b1b;
      }

      &:focus {
        border-color: #f76b1b;
        box-shadow: 0 0 0 3px rgba(247, 107, 27, 0.1);
        background: #ffffff;
      }

      &.has-value {
        border-color: #f76b1b;
        background: #ffffff;
      }

      &:disabled {
        background: #f0f0f0;
        border-color: #d0d0d0;
        color: #999;
        cursor: not-allowed;
      }
    }

    .error-message {
      text-align: center;
      margin-top: 12px;
      color: var(---, #ff4d4f);
      text-align: center;
      font-family: 'Inter Tight';
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }
  }

  // 响应式设计
  @media (max-width: 480px) {
    .verification-code-input {
      .code-inputs {
        gap: 16px;
      }

      .code-digit {
        width: 40px;
        height: 40px;
        font-size: 16px;
      }
    }
  }
</style>
